package wjx.database.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;

import wjx.database.bean.JTableUtils;
import wjx.database.jdbc.JDBCUtils;

public class EditFrm extends JFrame {

	private int num;
	private int count = 0;

	private JPanel contentPane;
	private JLabel label1, label2, label3, label;
	private Box box, box1, box2, box3, box4, box5, box7;
	private JButton button1, button2, button3;
	private JTable table1, table2;
	private JScrollPane scroll1, scroll2;
	private DefaultTableModel modelE;

	private String[] listName;
	private String[] qQuery;
	private String[] type;
	private static List<String> primaryK = new ArrayList<>();
	private String title;
	private String sql;
	private String tableName;
	private String[][] data = null;
	private ResultSet rs;
	private String editValue = "";
	private String code = "";

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					EditFrm frame = new EditFrm("new_table");
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public EditFrm(String name) {
		code = JDBCUtils.GetTableRemarks(name);
		tableName = name;
		primaryK = JDBCUtils.GetPriKey(name);
		setTitle("修改-表'" + name +"'");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setResizable(false);
		setBounds(100, 100, 700, 600);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));

		// 获取表字段名和对应类型
		List<String> queryList = JDBCUtils.GetTableColAnd(name);
		String[] mid = new String[queryList.size()];
		queryList.toArray(mid);

		qQuery = new String[queryList.size() / 2];
		type = new String[queryList.size() / 2];
		queryList.toArray(mid);
		for (int i = 0; i < queryList.size() / 2; i++) {
			qQuery[i] = mid[2 * i];
			type[i] = mid[2 * i + 1];
		}

		listName = new String[qQuery.length];
		num = qQuery.length;
		for (int i = 0; i < num; i++) {
			if( code.equals(qQuery[i])) {
				listName[i] = qQuery[i] + '(' + type[i] + "[加密列])";
				continue ;
			}
			listName[i] = qQuery[i] + '(' + type[i] + ')';
			
		}

		// 显示查找条件table1
		label = new JLabel("查找想要修改的记录(支持<、>、=条件查询)");
		label.setFont(new Font("Lucida Grande", 1, 15));
		title = " select * from databaseManager." + name;
		label1 = new JLabel(title);
		label2 = new JLabel(" where ");

		table1 = new JTable(1, num);
		DefaultTableModel model = (DefaultTableModel) table1.getModel();
		model.setColumnIdentifiers(listName);
		table1.setModel(model);
		JTableUtils.setTable(table1);
		scroll1 = new JScrollPane(table1);
//		table1.setPreferredScrollableViewportSize(new Dimension(num * 100, 32));
		scroll1.setPreferredSize(new Dimension(700,65));

		// 加载数据
		try {
			rs = JDBCUtils.query(title);
			// 加载data
			rs.last();
			data = new String[rs.getRow()][qQuery.length];
			rs = JDBCUtils.query(title);
			int cnt = 0;
			while (rs.next()) {
				for (int j = 0; j < qQuery.length; j++) {
					data[cnt][j] = rs.getString(qQuery[j]);
					if(code.equals(qQuery[j])) {
						MainFrm.myt.getEn(data[cnt][j]);
						synchronized(MainFrm.myt){
							MainFrm.myt.wait();
						}
						data[cnt][j] += '(' + MainFrm.myt.res + ')';
					}
					System.out.println(data[cnt][j]);
				}
				cnt++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// table2显示表的全部数据
		table2 = new JTable() {
			private static final long serialVersionUID = 1L;

			public void editingStopped(ChangeEvent changeevent) {
				int r = getEditingRow();
				int c = getEditingColumn();
				editValue = (String) table2.getValueAt(r, c);
				System.out.println(editValue);
				TableCellEditor tablecelleditor = getCellEditor();
				if (tablecelleditor != null) {
					Object obj = tablecelleditor.getCellEditorValue();
					setValueAt(obj, editingRow, editingColumn);
					removeEditor();
				}
			}

		};

		modelE = new DefaultTableModel(data, qQuery);
		table2.setModel(modelE);
//		table2.setPreferredScrollableViewportSize(new Dimension(num * 100, 120));
		JTableUtils.setTable(table2);
		scroll2 = new JScrollPane(table2);
		// 为表格绑定修改值后的事件
		modelE.addTableModelListener(new TableModelListener() {
			public void tableChanged(TableModelEvent e) {
				editPerform(e);
			}
		});

		button1 = new JButton("查找");
		button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				queryActionPerformed(e);
			}
		});

		button3 = new JButton("重置");
		button3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				clearActionPerformed(e);
			}
		});

		button2 = new JButton("退出");
		button2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				quitActionPerformed(e);
			}
		});

		label3 = new JLabel("查询到符合您输入条件的结果如下");
		label3.setFont(new java.awt.Font("Lucida Grande", Font.PLAIN, 16));
		JLabel lb = new JLabel("(点击表格即可进行修改)");
		lb.setFont(new Font("Lucida Grande", 1, 13));
		// 箱式布局
		box1 = Box.createHorizontalBox();
		box1.add(label);
		box2 = Box.createHorizontalBox();
		box2.add(label1);
		box2.add(label2);

		box5 = Box.createHorizontalBox();
		box5.add(scroll1);

		box3 = Box.createHorizontalBox();
		box3.add(button1);
		box3.add(button3);
		box3.add(button2);

		box7 = Box.createHorizontalBox();
		box7.add(label3);
		Box bx1 = Box.createHorizontalBox();
		bx1.add(lb);

		box4 = Box.createHorizontalBox();
		box4.add(scroll2);

		box = Box.createVerticalBox();
		box.add(box1);
		box.add(Box.createVerticalStrut(5));
		box.add(box2);
		box.add(Box.createVerticalStrut(10));
		box.add(box5);
		box.add(box3);
		box.add(Box.createVerticalStrut(10));
		box.add(box7);
		box.add(bx1);
		box.add(Box.createVerticalStrut(5));
		box.add(box4);

		contentPane.add(box);
		setContentPane(contentPane);
//		pack();
		this.setLocationRelativeTo(null);
	}

	private void editPerform(TableModelEvent e) {
		if(qQuery[e.getColumn()].equals(code)) {
			JOptionPane.showMessageDialog(null, "抱歉，您没有权限修改加密列。");
			return ;
		}
		String nVal = table2.getValueAt(e.getFirstRow(), e.getColumn()).toString();
		// 如果旧的值 和新的值一样，直接返回
		if (nVal.equals(editValue)) {
			return;
		}

		sql = "update databaseManager." + tableName + " set ";
		String cond = " where ";
		int len = primaryK.size();
		int lie, hang;
		String[] ns = new String[len];
		primaryK.toArray(ns);
		for (int i = 0; i < len; i++) {
			if (i > 0)
				cond += " AND ";
			System.out.println(ns[i]);
			lie = modelE.findColumn(ns[i]);
			hang = e.getFirstRow();
			System.out.println("hang:" + hang + " lie:" + lie);

			if (lie == e.getColumn()) {
				if (type[lie].charAt(0) == 'V')
					cond += ns[i] + "='" + editValue + "'";
				else
					cond += ns[i] + "=" + editValue;
				continue ;
			}
			if (type[lie].charAt(0) == 'V')
				cond += ns[i] + "='" + table2.getValueAt(hang, lie).toString() + "'";
			else
				cond += ns[i] + "=" + table2.getValueAt(hang, lie).toString();
		}
		System.out.println(cond);

		// 监听table2编辑事件
		if (e.getColumn() < 0)
			return;
		
		
		if (type[e.getColumn()].charAt(0) == 'V')
			sql += qQuery[e.getColumn()] + "='" + nVal + "'" + cond;
		else
			sql += qQuery[e.getColumn()] + "=" + nVal + cond;
		System.out.println(sql);

		// 执行数据修改操作
		try {
			count = JDBCUtils.update(sql);
			if (count > 0)
				JOptionPane.showMessageDialog(null, "修改成功！");
			else
				JOptionPane.showMessageDialog(null, "无法修改！");
		} catch (SQLException e1) {
			JOptionPane.showMessageDialog(null, "修改失败！请检查修改后的数据类型是否符合要求！");
		}

	}

	private void clearActionPerformed(ActionEvent e) {
		for (int i = 0; i < num; i++) {
			table1.setValueAt("", 0, i);
		}
	}

	private void quitActionPerformed(ActionEvent e) {
		// 退出
		int result = JOptionPane.showConfirmDialog(null, "是否退出修改？", "退出修改", JOptionPane.YES_NO_OPTION);
		// 退出窗口
		if (result == JOptionPane.YES_NO_OPTION)
			dispose();

	}

	private void queryActionPerformed(ActionEvent e) {
		sql = title;
		String s;
		int cnt = 0;
		for (int i = 0; i < num; i++) {
			s = (String) table1.getValueAt(0, i);
			System.out.println("$value" + s);
			if (s == null || s.length() == 0)
				continue;
			if (cnt == 0)
				sql += " where ";
			if (cnt > 0)
				sql += " AND ";
			sql += qQuery[i] + s;
			cnt++;
		}
		// 获取查询条件
		System.out.println("query :" + sql);

		try {
			rs = JDBCUtils.query(sql);
			rs.last();
			data = new String[rs.getRow()][qQuery.length];
			rs = JDBCUtils.query(sql);
			int cnt_ = 0;
			while (rs.next()) {
				for (int j = 0; j < qQuery.length; j++) {
					data[cnt_][j] = rs.getString(qQuery[j]);
					if(code.equals(qQuery[j])) {
						MainFrm.myt.getEn(data[cnt_][j]);
						synchronized(MainFrm.myt){
							MainFrm.myt.wait();
						}
						data[cnt_][j] += '(' + MainFrm.myt.res + ')';
					}
					System.out.println(data[cnt_][j]);
				}
				cnt_++;
			}
		} catch (Exception e1) {
			JOptionPane.showMessageDialog(null, "语法错误！请检查您的输入！");
		}
		// 显示查询结果
		table2 = new JTable();
		modelE = new DefaultTableModel(data, qQuery);
		table2.setModel(modelE);
//		table2.setPreferredScrollableViewportSize(new Dimension(num * 100, 120));
		JTableUtils.setTable(table2);
		// 为表格绑定修改值后的事件
		modelE.addTableModelListener(new TableModelListener() {
			public void tableChanged(TableModelEvent e) {
				editPerform(e);
			}
		});

		box.remove(box4);
		scroll2 = new JScrollPane(table2);

		box4.removeAll();
		box4.add(scroll2);

		box.add(box4);
		contentPane.add(box);
		remove(contentPane);

		setContentPane(contentPane);
//		pack();

		// 不可编辑

	}

}
